/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.sprite.sheet;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.geom.Rectangle;
import hapi.sprite.blit.BlitBitmapSpriteSheetDisplay;
import hapi.sprite.display.BitmapSpriteSheetDisplay;
import hapi.sprite.display.CopyPixelsSpriteSheetDisplay;
import hapi.sprite.display.SpriteSheetDisplay;

class CopyPixelsSpriteSheet extends SpriteSheetBase, implements DrawOnBitmapSpriteSheet {
	
	var rect:Rectangle;
	var mergeAlpha:Bool;
	
	public function new(source:BitmapData, width:Int, height:Int, ?mergeAlpha=false) {
		super(source, width, height);
		this.mergeAlpha = mergeAlpha;
		this.rect = new Rectangle(0, 0, width, height);
	}
	
	public inline function drawSpriteOn(canvas:Bitmap, spriteId:Int, dest:Point):Void {
		updateCurrentSprite(spriteId);
		canvas.bitmapData.copyPixels(source, rect, dest, null, null, mergeAlpha);
	}
	
	inline function updateCurrentSprite(spriteId:Int) {
		if(currentSpriteId != spriteId) {
			var row = Math.ceil(spriteId/cols);
			var col = spriteId - (cols * (row - 1));
			rect.x = (col- 1) * width;
			rect.y = (row -1) * height;
			currentSpriteId = spriteId;
		}
	}
	
	public function createDisplay(?x:Float=0.0, ?y:Float=0.0):SpriteSheetDisplay {
		return createBitmapDisplay(x, y);
	}
	
	public function createBitmapDisplay(?x:Float = 0.0, ?y:Float = 0.0):BitmapSpriteSheetDisplay {
		return new CopyPixelsSpriteSheetDisplay(this, x, y);
	}
	
	public function createBlitDisplay(?x:Float, ?y:Float):BlitBitmapSpriteSheetDisplay {
		return new BlitBitmapSpriteSheetDisplay(this, x, y);
	}
}